package com.slz3.business.module.systemManagement.sysOrganize.service;

import com.slz3.business.frame.enums.ValidFlag;
import com.slz3.business.frame.module.Repositorys;
import com.slz3.business.frame.module.Services;
import com.slz3.business.frame.steward.PageableSteward;
import com.slz3.business.module.systemManagement.sysOrganize.domain.SysOrganize;
import com.slz3.business.module.systemManagement.sysOrganize.domain.SysOrganizeFactory;
import com.slz3.business.module.systemManagement.sysOrganize.steward.SysOrganizeSpecification;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SysOrganizeServiceImpl implements SysOrganizeService {

    @Override
    public SysOrganize save(SysOrganize sysOrganize) {
        return Repositorys.sysOrganize.save(SysOrganizeFactory.initBaseFields(sysOrganize));
    }

    @Override
    public Page<SysOrganize> page(MultiValueMap<String, String> params) {
        Page<SysOrganize> sysOrganizePage = Repositorys.sysOrganize.findAll(
                SysOrganizeSpecification.findJoin(params), PageableSteward.extract(params)
        );
        Map<UUID, SysOrganize> collect = Repositorys.sysOrganize.findAllById(
                sysOrganizePage.stream().map(SysOrganize::getParentId)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList())
        ).stream().collect(Collectors.toMap(SysOrganize::getUuid, Function.identity()));
        sysOrganizePage.stream().forEach(item -> item.setParentOrganize(collect.get(item.getParentId())));
        return sysOrganizePage;
    }

    @Override
    public SysOrganize modify(SysOrganize sysOrganizeNew) {
        return Repositorys.sysOrganize.saveAndFlush(SysOrganizeFactory.initBaseFields(sysOrganizeNew));
    }

    @Override
    public Optional<SysOrganize> single(UUID uuid) {
        return Repositorys.sysOrganize.findById(uuid);
    }

    @Override
    public List<SysOrganize> findAllByUuids(Iterable<UUID> uuids) {
        return Repositorys.sysOrganize.findAllById(uuids);
    }

    @Override
    public List<SysOrganize> delete(List<SysOrganize> sysOrganizeList) {
        sysOrganizeList.stream().forEach(item -> {
            item.setValidFlag(ValidFlag.DEL);
            SysOrganizeFactory.initBaseFields(item);
        });
        return Services.sysOrganizeTransactional.batchModify(sysOrganizeList);
    }

    @Override
    public List<SysOrganize> findAll(SysOrganize param) {
        param.setValidFlag(ValidFlag.VALID);
        return Repositorys.sysOrganize.findAll(Example.of(param));
    }
}
